package com.sfh.pst.beauty;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sfh.base.ApplicationEntity;
import com.sfh.base.http.server.ExceptionHandle;
import com.sfh.entity.Beauty;
import com.sfh.entity.BeautyJson;
import com.sfh.pst.IPstBeauty;
import com.sfh.pst.http.AbstractHttpPresenter;
import com.sfh.pst.http.AppSyncSubscriber;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscription;
import rx.functions.Func1;

/**
 * 功能描述:
 *
 * @date 2017/9/4
 */
public class PstUserBeautyList extends AbstractHttpPresenter<IPstBeauty.IPstUserBeautyList.IVUserBeautyList> implements IPstBeauty.IPstUserBeautyList {

    @Override
    public void queryUserBeauty() {

        if (isNoAttach ()) {
            return;
        }

        Observable observable = Observable.just ("").map (new Func1<String, List<Beauty>> () {

            @Override
            public List<Beauty> call(String s) {

                List<Beauty> list = new ArrayList<> ();
                try {
                    InputStreamReader input = new InputStreamReader (ApplicationEntity.getApplication ().getResources ().getAssets ().open ("wives.json"));
                    BufferedReader bufReader = new BufferedReader (input);
                    String line = "";
                    StringBuffer result = new StringBuffer ();
                    while ((line = bufReader.readLine ()) != null) {
                        result.append (line);
                    }

                    Gson gson = new Gson ();
                    List<BeautyJson> tempList = gson.fromJson (result.toString (), new TypeToken<List<BeautyJson>> () {

                    }.getType ());

                    for(BeautyJson beautyJson : tempList){
                        Beauty beauty = new Beauty ();
                        beauty.setBeauty (beautyJson);
                        list.add (beauty);

                    }

                } catch (IOException e) {
                    e.printStackTrace ();
                }

                return list;
            }
        });
        Subscription subscription = execute (observable, new AppSyncSubscriber<List<Beauty>> () {

            @Override
            public void onSuccee(List<Beauty> result) throws Exception {

                getView ().setList (result);
            }

            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {

            }
        });

        this.putSubscribe (subscription);
    }
}
